package com.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reggie.pojo.User;
import com.reggie.service.UserService;
import com.reggie.utils.BaseContext;
import com.reggie.utils.Result;
import com.reggie.utils.SMSUtils;
import com.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author zhaoyuheng
 * @email 2646498606@qq.com
 * @date 2022/4/27 10:39
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送手机验证码
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user, HttpSession session) {
        //获取手机号
        String phone = user.getPhone();

        if (phone == null) {
            return Result.error("手机号为空");
        }
        //生成随机验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();

        //调用阿里云的短信发送业务
//        SMSUtils.sendMessage("阿里云短信测试",
//                "SMS_154950909",
//                phone,code);
        System.out.println(code);

        //需要将验证码保存到session中
        session.setAttribute(phone, code);

        //验证码校验
        return Result.success("手机验证码已发送");
    }

    /**
     * 登陆验证
     *
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public Result<User> login(@RequestBody Map<String, String> map, HttpSession session) {
        //获取手机号
        String phone = map.get("phone");
        //获取验证码
        String code = map.get("code");
        //从session中获取保存的验证码做比对，比对成功登录，不成功失败,当时存的数据是 ： phone ： code
        String sessionCode = String.valueOf(session.getAttribute(phone));
        if (sessionCode.equals(code) && sessionCode != null) {
            //判断当前手机号是或否存在Use表中，如果不存在，就直接保存到表里
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone, phone);

            User user = userService.getOne(wrapper);

            if (user == null) {
                //自动注册
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                user.setName("用户名");
                userService.save(user);
            }
            //登录信息储存到session中
            session.setAttribute("user",user.getId());

            log.info("登陆成功，用户Id：{}",session.getAttribute("user"));

            //验证码正确
            return Result.success(user);
        }
        return Result.error("登陆失败");
    }

    /**
     * 退出登录
     * @param session
     * @return
     */
    @PostMapping("/loginout")
    public Result<String> loginout(HttpSession session) {
        //删除当前登录用户的session
        session.removeAttribute("user");
        //清除线程中保留的用户Id
        BaseContext.removeCurrent();

        return Result.success("退出登录");
    }

    /**
     * 获取用户信息
     * @param userPhone
     * @return
     */
    @GetMapping("/{userPhone}")
    public Result<User> getUser(@PathVariable String userPhone) {
        //根据电话号码查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,userPhone);

        User user = userService.getOne(wrapper);
        return Result.success(user);
    }
}
